<template>
  <div class="space-y-4">
    <div class="flex flex-col sm:flex-row justify-between items-stretch sm:items-center gap-3">
      <div class="flex gap-2">
        <button class="btn-primary flex-1" :class="{ 'opacity-60': mode==='grid' }" @click="mode='grid'">网格视图</button>
        <button class="btn-primary flex-1" :class="{ 'opacity-60': mode==='list' }" @click="mode='list'">列表视图</button>
      </div>
      <div class="flex flex-col sm:flex-row items-stretch sm:items-center gap-2">
        <input type="file" ref="fileRef" class="hidden" accept="image/*,video/*" @change="onPick" />
        <input v-model="desc" class="input flex-1" placeholder="描述（可选）" />
        <button class="btn-accent" @click="triggerPick">上传媒体</button>
      </div>
    </div>

    <div v-if="loading" class="text-center text-gray-500">加载中...</div>
    <template v-else>
      <div v-if="mode==='grid'" class="grid grid-cols-2 md:grid-cols-4 gap-3">
        <div v-for="m in media" :key="m.id" class="relative group">
          <img 
            v-if="m.contentType.startsWith('image/')" 
            :src="mediaUrl(m.objectKey)" 
            class="w-full aspect-square object-cover rounded cursor-pointer hover:opacity-90 transition-opacity" 
            @error="handleImageError"
            @click="openPreview(m)"
            :alt="m.description || '媒体文件'"
          />
          <video v-else :src="mediaUrl(m.objectKey)" class="w-full aspect-square object-cover rounded" controls />
          <button class="absolute top-2 right-2 px-2 py-1 rounded bg-black/60 text-white opacity-0 group-hover:opacity-100" @click="remove(m.id)">删除</button>
        </div>
      </div>
      <div v-else class="space-y-3">
        <div v-for="m in media" :key="m.id" class="card flex items-center gap-3">
          <img 
            v-if="m.contentType.startsWith('image/')" 
            :src="mediaUrl(m.objectKey)" 
            class="w-20 h-20 object-cover rounded cursor-pointer hover:opacity-90 transition-opacity" 
            @error="handleImageError"
            @click="openPreview(m)"
            :alt="m.description || '媒体文件'"
          />
          <video v-else :src="mediaUrl(m.objectKey)" class="w-20 h-20 object-cover rounded" controls />
          <div class="flex-1">
            <div>{{ m.description || '无描述' }}</div>
            <div class="text-sm text-gray-500">{{ fmt(m.createdAt) }}</div>
          </div>
          <button class="px-3 py-1 rounded bg-bg hover:opacity-80" @click="remove(m.id)">删除</button>
        </div>
      </div>
    </template>

    <!-- 图片预览模态框 -->
    <div v-if="previewModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/80" @click="closePreview">
      <div class="relative max-w-4xl max-h-[90vh] w-full mx-4" @click.stop>
        <button 
          class="absolute top-4 right-4 z-10 w-8 h-8 rounded-full bg-black/60 text-white flex items-center justify-center hover:bg-black/80 transition-colors"
          @click="closePreview"
        >
          ✕
        </button>
        <img 
          :src="previewImage?.src" 
          :alt="previewImage?.description || '预览图片'"
          class="w-full h-full object-contain rounded"
          @error="handlePreviewError"
        />
        <div v-if="previewImage?.description" class="absolute bottom-4 left-4 right-4 bg-black/60 text-white p-3 rounded">
          {{ previewImage.description }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch } from 'vue';
import { useUserStore } from '../stores/user';
import { type MediaAsset, API_CONFIG } from '../services/api';

// 临时解决方案：直接定义函数
async function listMedia(babyId: number) {
  const token = localStorage.getItem('auth_token');
  console.log('Gallery listMedia - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/media/list?babyId=${babyId}`, {
    headers: {
      'Authorization': `Bearer ${token || ''}`
    }
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

async function uploadMedia(payload: { babyId: number; file: File; description?: string }) {
  const token = localStorage.getItem('auth_token');
  console.log('Gallery uploadMedia - token:', token);
  const form = new FormData();
  form.append('babyId', String(payload.babyId));
  form.append('file', payload.file);
  if (payload.description) form.append('description', payload.description);
  
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/media/upload`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token || ''}`
    },
    body: form
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

async function deleteMedia(id: number) {
  const token = localStorage.getItem('auth_token');
  console.log('Gallery deleteMedia - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/media/${id}`, {
    method: 'DELETE',
    headers: {
      'Authorization': `Bearer ${token || ''}`
    }
  });
  if (!resp.ok && resp.status !== 204) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
}

function buildMediaUrl(objectKey: string): string {
  console.log('Gallery buildMediaUrl - base:', API_CONFIG.MEDIA_BASE, 'objectKey:', objectKey);
  // 使用统一的媒体基础URL配置
  return `${API_CONFIG.MEDIA_BASE}/${objectKey}`;
}

const userStore = useUserStore();
const mode = ref<'grid' | 'list'>('grid');
const loading = ref(false);
const media = ref<MediaAsset[]>([]);
const fileRef = ref<HTMLInputElement | null>(null);
const desc = ref('');

// 图片预览相关
const previewModal = ref(false);
const previewImage = ref<{ src: string; description?: string } | null>(null);

function mediaUrl(objectKey: string) { return buildMediaUrl(objectKey); }
function fmt(iso: string) { const d = new Date(iso); return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')} ${d.toTimeString().slice(0,5)}`; }

function handleImageError(event: Event) {
  const img = event.target as HTMLImageElement;
  console.error('图片加载失败:', img.src);
  // 可以在这里添加错误处理逻辑，比如显示占位符
  img.style.display = 'none';
}

// 图片预览功能
function openPreview(mediaItem: MediaAsset) {
  if (mediaItem.contentType.startsWith('image/')) {
    previewImage.value = {
      src: mediaUrl(mediaItem.objectKey),
      description: mediaItem.description
    };
    previewModal.value = true;
  }
}

function closePreview() {
  previewModal.value = false;
  previewImage.value = null;
}

function handlePreviewError(event: Event) {
  const img = event.target as HTMLImageElement;
  console.error('预览图片加载失败:', img.src);
  // 可以显示错误提示
  closePreview();
}

async function load() {
  console.log('Gallery load - currentBabyId:', userStore.currentBabyId);
  console.log('Gallery load - currentUser:', userStore.currentUser);
  console.log('Gallery load - familyBabies:', userStore.familyBabies);
  console.log('Gallery load - VITE_PUBLIC_MEDIA_BASE:', import.meta.env.VITE_PUBLIC_MEDIA_BASE);
  
  if (!userStore.currentBabyId) {
    console.log('Gallery: 没有选择宝宝，无法加载媒体');
    return;
  }
  
  loading.value = true;
  try {
    console.log('Gallery: 开始加载媒体列表...');
    media.value = await listMedia(userStore.currentBabyId);
    console.log('Gallery: 媒体列表加载成功:', media.value);
  } catch (error) {
    console.error('Gallery: 加载媒体失败:', error);
  } finally {
    loading.value = false;
  }
}

function triggerPick() { fileRef.value?.click(); }
async function onPick(e: Event) {
  if (!userStore.currentBabyId) return;

  const input = e.target as HTMLInputElement;
  const file = input.files?.[0];
  if (!file) return;
  await uploadMedia({ babyId: userStore.currentBabyId, file, description: desc.value || undefined });
  desc.value = '';
  input.value = '';
  await load();
}

async function remove(id: number) {
  await deleteMedia(id);
  await load();
}

// 监听宝宝切换，重新加载数据
watch(() => userStore.currentBabyId, () => {
  if (userStore.currentBabyId) {
    load();
  }
});

// 键盘事件处理
function handleKeydown(event: KeyboardEvent) {
  if (event.key === 'Escape' && previewModal.value) {
    closePreview();
  }
}

onMounted(() => {
  load();
  document.addEventListener('keydown', handleKeydown);
});

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown);
});
</script>

<style scoped></style>